const express = require("express");
const fs = require("fs");
const userRouter = express.Router();
const {uploadfile} = require("../util");
const md5 = require("md5");
const userModel = require("../models/usersModel");

let perpage = 3; // 每页显示的条数

userRouter.get("/test",(req,res)=>{
    
    res.json({
        info:"测试文件",
        status:1
    })
})

userRouter.post("/adduser",async (req,res)=>{
    try {
        let obj = await uploadfile(req);
        obj.time = new Date().toLocaleDateString();
        obj.pwd = md5(obj.pwd);
        await userModel.create(obj);
        let data = await userModel.find();
        res.json({
            info: "添加成功",
            status: 1,
            p:Math.ceil(data.length/perpage)
        })
    }catch(err){
        res.json({
            info:"添加失败",
            status:0
        })
    }

})

userRouter.get("/getusers",async (req,res)=>{
    let {p = 1} = req.query;  // 当前页面，默认在第一页 
    // console.log("当前",p);
    let data = await userModel.find();
    let pageCount = Math.ceil(data.length/perpage);
    let users = await userModel.find().skip((p-1)*perpage).limit(perpage);
    res.json({users,pageCount});  // 通过ajax返还给前端；
})



userRouter.delete("/deluser",async (req,res)=>{
    let {_id,img} = req.query;
    try{
        // console.log(img);
        let delurl = process.cwd()+"/static/"+img;
        if(fs.existsSync(delurl)){  // 判断 文件是否存在 ，如果存在就删除；
            fs.unlinkSync(delurl);
        }
        await userModel.deleteOne({_id});
        res.json({
            info:"删除成功",
            status:1
        })
    }catch(err){
        console.log(err);
        res.json({
            info:"删除失败",
            status:0,
            err
        })
    }
})

module.exports = userRouter;